package edu.nf.project.services.other.impl;

import edu.nf.project.entitys.entity.other.Message;
import edu.nf.project.mappers.other.MessageMapper;
import edu.nf.project.services.exception.derivedAnomalies.MessageException;
import edu.nf.project.services.other.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;

    @Override
    @Transactional
    public void sendMessage(Message message) {
        if (message == null || message.getContent() == null || message.getContent().trim().isEmpty()) {
            throw new MessageException(80000, "消息内容不能为空");
        }
        if (message.getSender() == null || message.getSender().trim().isEmpty()) {
            throw new MessageException(80000, "发送者不能为空");
        }
        if (message.getReceiver() == null || message.getReceiver().trim().isEmpty()) {
            throw new MessageException(80000, "接收者不能为空");
        }
        
        // 设置发送时间
        if (message.getSendTime() == null) {
            message.setSendTime(new Date());
        }
        
        // 使用MyBatis-Plus的insert方法
        int result = messageMapper.insert(message);
        if (result != 1) {
            throw new MessageException(80000, "消息发送失败");
        }
    }

    @Override
    public List<Message> getChatHistory(String sender, String receiver) {
        if (sender == null || sender.trim().isEmpty()) {
            throw new MessageException(80001, "发送者不能为空");
        }
        if (receiver == null || receiver.trim().isEmpty()) {
            throw new MessageException(80001, "接收者不能为空");
        }
        
        return messageMapper.getMessagesBySenderAndReceiver(sender, receiver);
    }

    @Override
    public List<Message> getAllChats(String receiver) {
        if (receiver == null || receiver.trim().isEmpty()) {
            throw new MessageException(80002, "接收者不能为空");
        }
        
        return messageMapper.getAllMessagesByReceiver(receiver);
    }
}
